/* Copyright © 2010 LPRM
Universidade Federal do Espírito Santo - RNP-GT CWTools

This file is part of JoinUs!.

JoinUs! is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

JoinUs! is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with JoinUs!. If not, see <http://www.gnu.org/licenses/>. */
package br.ufes.cwtools.joinus.home.communities;

import java.io.IOException;
import java.io.StringReader;
import java.util.Vector;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import br.ufes.cwtools.joinus.util.ServerCom;

import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import br.ufes.cwtools.joinus.R;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;  //import android.view.ViewInflate;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MembersList {
	LayoutInflater viewInflate; //	ViewInflate viewInflate;
	ListView v;
	long[] keys;
	long commuId;
	SQLiteDatabase myBase;
	final String user;

	public void Load() {
		String xml = ServerCom.listCommuMembers(commuId + "");
		InputSource is = new InputSource();

		if (xml == null) {
			myBase.execSQL("DELETE FROM communities WHERE id=" + commuId
					+ " and user='" + user + "';");
			return;
		}

		is.setCharacterStream(new StringReader(xml));
		Members factory = new Members();
		Vector<Long> members = factory.fromXml(is);
		final String[][] array = new String[members.size()][];
		keys = new long[members.size()];
		int count = 0;
		for (Long l : members) {
			Log.d("MEMBERS", l.toString());
			array[count] = new String[2];
			array[count][0] = "Name: " + ServerCom.getUserName(l.toString());
			keys[count] = l;
			array[count][1] = "User id: " + l.toString();
			count++;
		}
		add(array);
	}

	public MembersList(final long commuId, Activity a, SQLiteDatabase myBase,
			String user) {
		this.user = user;
		this.myBase = myBase;
		this.commuId = commuId;
		viewInflate = LayoutInflater.from(a);  //viewInflate = ViewInflate.from(a);
		a.setContentView(R.layout.members);
		v = (ListView) a.findViewById(R.id.members_list_view);
		Load();
		Button kick = (Button) a.findViewById(R.id.members_but);
		kick.setOnClickListener(new OnClickListener() {
			//int i = 0;

			public void onClick(View arg0) {
				for (int i = 0; i < v.getAdapter().getCount(); i++) {
					RelativeLayout r = (RelativeLayout) v.getChildAt(i);
					CheckBox cb = (CheckBox) r.getChildAt(0);
					if (cb.isChecked()) {
						Log.d("KICKING", "Kicking" + keys[i] + " from "
								+ commuId);
						if (ServerCom.quitCommu(commuId + "", keys[i] + ""))
							Load();
					}
				}
			}
		});
	}

	public void add(String[][] toAdd) {
		RelativeLayout[] rl = new RelativeLayout[toAdd.length];
		for (int i = 0; i < toAdd.length; i++) {
			RelativeLayout r = (RelativeLayout) viewInflate.inflate(R.layout.line_template, null);
			// RelativeLayout r = (RelativeLayout) viewInflate.inflate(R.layout.line_template, null, null);
			((TextView) r.getChildAt(1)).setText(toAdd[i][0]);
			((TextView) r.getChildAt(2)).setText(toAdd[i][1]);
			rl[i] = r;
		}
		v.setAdapter(new MyListAdapter(rl));
	}

	final class MyListAdapter extends BaseAdapter {
		RelativeLayout[] item;

		public MyListAdapter(RelativeLayout[] v) {
			item = v;
		}

		public Object getItem(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			return item[position];
		}

		public long getItemId(int position) {
			return position;
		}

		public int getCount() {
			return item.length;
		}
	}
}

class Members {
	Vector<Long> members = new Vector<Long>();

	public Vector<Long> fromXml(InputSource xml) {
		try {
			SAXParserFactory spf = SAXParserFactory.newInstance();
			SAXParser sp;
			sp = spf.newSAXParser();
			XMLReader xr = sp.getXMLReader();
			MyHandler handler = new Members.MyHandler();
			xr.setContentHandler(handler);
			xr.setErrorHandler(handler);
			xr.parse(xml);
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}

		return members;
	}

	class MyHandler extends DefaultHandler {
		String lastElement;
		boolean begin;
		boolean valid;
		int count = 0;

		public void endElement(String uri, String localName, String qName) {
			begin = false;
		}

		public void startElement(String uri, String localName, String qName, Attributes attributes) {
			begin = true;
			if (localName.compareTo("Members") == 0) {
				count++;
				valid = true;
			}
			lastElement = localName;
			for (int i = 0; i < attributes.getLength(); i++) {
				lastElement = attributes.getValue(i);
				// Log.d("DEBUG","*******"+lastElement);
			}
		}

		public void characters(char[] ch, int start, int length) {
			if (valid) {
				String s = new String(ch, start, length);
				if (lastElement == null)
					return;
				if (!begin)
					return;
				if (lastElement.compareTo("Member") == 0) {
					if (s.compareTo("null") != 0) {
						// Log.d("DEBUG","id:"+s);
						members.add(new Long(Integer.parseInt(s)));
					}
				}
			}
		}
	}
}
